Ext.define('cfWeb.controller.dataStorage.DataStorageController', {
	extend : 'Ext.app.Controller',
	views : ['dataStorage.DataStorageView', 'dataStorage.NewDatabaseView',
			'cfWeb.cfWebComponent.LbuttonIconListView',
			'cfWeb.cfWebComponent.CollapsibleBlock',
	        'cfWeb.cfWebComponent.CbuttonIconListView',
	        'cfWeb.view.dataStorage.DataStorageView',
	        'cfWeb.cfWebComponent.HeadView',
	        'cfWeb.view.dataStorage.DataStorageDetailView'
			],
	stores : ['dataStorage.DatabaseServiceStore',
	          'dataStorage.DatabaseServiceBrokerStore',
	          'dataStorage.DatabaseBrokerPlanStore'],
	init : function() {
		this.control({
			'dataStorageView collapsibleBlock cbuttonIconListView#databaselist' : {
				render : this.viewRender,
		//		appClick : this.databaseDetails,
				menuClick : this.actionRouter
			},
			'dataStorageView lbuttonIconListView' : {
				menuClick : this.menuClickAct
			},
			
			'newDatabaseView combobox[itemId=serviceName]':{
				change : this.serviceChange
			},
			'newDatabaseView':{
				onSubmit:this.createService
			},
			'dataStorageView collapsibleBlock' : {
				onSearch : this.onsearch,
				clearSearch : this.search
			}
		});
	},
	actionRouter : function(me,act,name,index,e){
		
	},
	databaseDetails : function(me,name,index,e){
		var store = me.getStore();
		var data = store.getAt(index);
		var mainView = Ext.ComponentQuery.query('mainView')[0];
		var win = Ext.widget('dataStorageDetailView',{
			adaptTo:mainView
		});
		win.slideIn();
		console.log(data);
	},
	createService:function(me){
		var serviceForm = me.down('form');
		var window = me;
		var publicValue = serviceForm.down('combobox[itemId=servicePlan]').getStore().getAt(0).get('public');
		var planId = serviceForm.down('combobox[itemId=servicePlan]').getStore().getAt(0).get('guid');
		console.log(planId);
		console.log(publicValue);
		console.log(me.serviceId);
		if(Ext.getCmp('databaselist')!=null){
			var waitWindow=Ext.MessageBox.show({title : cfWebLang.Util.CreateApp,closable: false,cls:'style-cfLoading'});
			var dbListStore = Ext.getCmp('databaselist').getStore();
		Ext.Ajax.request({
			url:'rest/service/createinstance',
			method:'POST',
			params:{
				service:serviceForm.getValues().service,
				plan:serviceForm.getValues().plan,
				planId:planId,
				prefix:me.prefix,
				visibility:publicValue,
				typeId:me.serviceId
			},
			success:function(res){
				var obj = Ext.JSON.decode(res.responseText);
				if(obj.success==true){
					window.close();
				    waitWindow.close();
				}else{
					waitWindow.close();
				    Ext.MessageBox.show({title:cfWebLang.Util.Tip,msg:cfWebLang.Util.CreateFailed,cls:'style-cfMessText',buttons: Ext.MessageBox.OK});
				}	
				dbListStore.load({
				  params:{
				   first:1
				  }
				});
			},
			failure:function(resp){
				waitWindow.close();
				dbListStore.load({
					  params:{
					  	first:1
					  }
					});
				if(resp.status=="401"){
			    	Ext.Msg.show({
			    	    title: cfWebLang.Util.Tip,
			    	    id:'firstWin',
			    	    msg: cfWebLang.Main.SessionOverdue,
			    	    width: 250,
			    	    buttons: Ext.MessageBox.OK,
			    	    fn: function(){  
			                parent.location.href = '/cfWeb/login.html';    
			            },
			            cls:'overtimeWin'
			    	});
			    	//Ext.WindowManager.bringToFront ('firstWin');
			       /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){  
			            parent.location.href = '/cfWeb/login.html';    
			        }); */
			       return;
			    }
			    
			    if(resp.timedout){  
			        Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
			        return;
			    }
				var error = Ext.JSON.decode(resp.responseText);
				if(error.data!=null&&error.data.source==1){
					 Ext.MessageBox.show({title:cfWebLang.ErrorSource.cloudfoundry,msg:error.data.message,cls:'style-cfMessText',buttons: Ext.MessageBox.OK});
			    }else{
					Ext.MessageBox.show({title:cfWebLang.ErrorSource.app,msg:cfWebLang.Error.SystemError,cls:'style-cfMessText',buttons: Ext.MessageBox.OK});
				}
				
			}
		
		});
		}
	},
	serviceChange:function(me){
		var store = me.up('newDatabaseView').store;
		var service = me.getValue();
		var planCombox = me.up('newDatabaseView').down('combobox[itemId=servicePlan]');
		var planStore = me.up('newDatabaseView').down('combobox[itemId=servicePlan]').getStore();
		planStore.loadData(store.findRecord('label',service).get("plans"));
		planCombox.setValue(planStore.getAt(0).get('name'));
	},
	menuClickAct : function(me, act, id) {
		var databaseBrokerStore = me.store.data.items;
		var itemId = act.itemId;
		var storeDatabase = Ext.getCmp('databaselist').getStore();
		storeDatabase.clearFilter();
		if (id == "new") {
			if(currentORG==null||currentORG==''){
				Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Util.OrgUnexit);
				return;
			}
			if(currentSpace==null||currentSpace==''){
				Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Util.SpaceUnexit);
				return;
			}
			var serviceWin = Ext.widget('newDatabaseView');
			var serviceBrokerStore = serviceWin.store;
			var storeServiceName = serviceWin.down('container').down('form')
					.down('combobox[itemId=serviceName]').getStore();
			for (var i = 0; i < databaseBrokerStore.length; i++) {
				if (databaseBrokerStore[i].data.id == itemId) {
					var prefix = databaseBrokerStore[i].data.serPrefix;
				    serviceWin.prefix = prefix;
				    serviceWin.serviceId = itemId;
					var serviceBroker = databaseBrokerStore[i].data.brokers;
					var brokers = null;
					for (var j = 0; j < serviceBroker.length; j++) {
						brokers = serviceBroker[j] + ','+brokers;
					}
					serviceBrokerStore.load({
								params : {
									lguid : brokers
								},
								callback : function(re) {
									storeServiceName.loadData(re);
									serviceWin.down('form').down('combobox[itemId=serviceName]')
			          .setValue(storeServiceName.getAt(0).get('label'));
								}
							});

				}
			}
			serviceWin.showAt(300,250,true);
		}
		if(id=="filter"){
			storeDatabase.filter("itemId",itemId);
			console.log(storeDatabase);
		}
	},
	viewRender : function(view) {
		view.getStore().load({
					params : {
						first : 1
					}
				});
	},
	onsearch : function(keyword, me){
		var title = me.title;
		
		if(title == cfWebLang.DataStorageView.dataStorage){
			var store = me.down('lbuttonIconListView').store;
			
			store.clearFilter();
			store.filter("itemName",new RegExp('/*'+keyword,"i"));
			
		}else if(title == cfWebLang.AppServiceView.AppServiceList){
			var store = me.down('cbuttonIconListView').store;
			store.clearFilter();
			store.filter("title",new RegExp('/*'+keyword,"i"));
		}
	},
	search : function(me){
		var title = me.title;
		
		if(title == cfWebLang.DataStorageView.dataStorage){
			var store = me.down('lbuttonIconListView').store;
			store.clearFilter();
		}else if(title == cfWebLang.AppServiceView.AppServiceList){
			var store = me.down('cbuttonIconListView').store;
			store.clearFilter();
		}
	}
});
